<template>
	<div class="Game_container">
		<div class="title">
			<button class="set" @click="settinter">设置</button>
			<div class="point">{{ currentLevelName }}</div>
			<div class="steps">步数: {{ moves }}</div>
		</div>

		<!-- 设置 -->
		<div class="settings" v-if="showsettings">
			<h3>设置</h3>
			<ul>
				<li>音乐<input type="checkbox" v-model="isMusicOn" /></li>
				<li>音效<input type="checkbox" v-model="isSoundEffectOn" /></li>
			</ul>
			<button @click="tiggleset">关闭</button>
		</div>

		<!-- 中间部分 -->
		<div class="game-container">
			<div class="button_left">
				<button @click="introduction">玩法介绍</button>
				<button @click="toggleRankingList">排行榜</button>
			</div>

			<!-- 排行榜弹窗 -->
			<div class="ranking-popup" v-if="showRankingList">
				<div class="ranking-header">
					<h3>排行榜</h3>
					<span class="close-btn" @click="closeRankingList">&times;</span>
				</div>
				<div class="ranking-content">
					<!-- 当前关卡进度 -->
					<div class="current-progress" v-if="currentLevel > 0">
						<h4>您的当前进度</h4>
						<p>第{{ currentLevel }}关 | 本关步数: {{ currentSteps }} | 累计步数: {{ currentPlayer.totalSteps }} |
							我的排名:
							{{ currentPlayer.rank }}
						</p>
					</div>
					<!-- 排序选项 -->
					<div class="sort-options">
						<label>排序方式: </label>
						<select v-model="sortBy">
							<option value="maxLevelDesc">最高关卡降序</option>
							<option value="totalStepsAsc">总步数升序</option>
						</select>
					</div>
					<table class="min-w-full divide-y divide-gray-200">
						<thead class="bg-gray-50">
							<tr>
								<th
									class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
									排名</th>
								<th
									class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
									用户名</th>
								<th
									class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
									最高关卡</th>
								<th
									class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
									总步数</th>
								<th
									class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
									注册时间</th>
							</tr>
						</thead>
						<tbody class="bg-white divide-y divide-gray-200">
							<tr v-for="(player, index) in sortedPlayers" :key="player.id" :class="{ 'current-player': player.id === currentPlayer.id,
                            'bg-yellow-100 font-bold': index === 0,
                            'bg-gray-100': index === 1,
                            'bg-orange-50': index === 2,
                            'hover:bg-gray-50': index > 2 }">
								<td class="px-4 py-3">
									<div :class="{
                    'w-6 h-6 rounded-full flex items-center justify-center bg-yellow-500 text-white': index === 0,
                    'w-6 h-6 rounded-full flex items-center justify-center bg-gray-400 text-white': index === 1,
                    'w-6 h-6 rounded-full flex items-center justify-center bg-orange-400 text-white': index === 2,
                    'w-6 h-6 rounded-full flex items-center justify-center bg-gray-200 text-gray-700': index > 2
                  }">
										{{ index + 1 }}
									</div>
								</td>
								<td class="px-4 py-3">{{ player.username }}</td>
								<td class="px-4 py-3">第{{ player.maxLevel }}关</td>
								<td class="px-4 py-3">{{ player.totalSteps }}</td>
								<td class="px-4 py-3">{{ new Date(player.registerTime).toLocaleString() }}</td>
							</tr>
						</tbody>
					</table>
				</div>
			</div>

			<!-- 游戏地图 -->
			<div class="map">
				<Gamemap :game-map="gamemap" @player-moved="recordPlayerMove" @level-complete="completeLevel" />
			</div>
		</div>

		<!-- 弹窗式完成提示 -->
		<transition name="modal">
			<div v-if="showCompletion" class="modal-mask">
				<div class="modal-wrapper">
					<div class="modal-container">
						<div class="modal-header">
							<h2 v-if="hasNextLevel">🎉 关卡完成！</h2>
							<h2 v-else>🏆 恭喜通关！</h2>
						</div>

						<div class="modal-body">
							<p v-if="hasNextLevel">使用步数: {{ moves }}</p>
							<p v-if="!hasNextLevel" class="congrats-message">你已完成 {{ LEVELS.length }} 个关卡！</p>

							<div class="progress-container" v-if="hasNextLevel">
								<div class="progress-bar">
									<div class="progress-fill" :style="{ width: progress + '%' }"></div>
								</div>
								<span>自动进入下一关 {{ progress }}%</span>
							</div>
						</div>

						<div class="modal-footer">
							<button v-if="hasNextLevel" class="modal-button next-btn" @click="goNextLevelNow">
								立即进入下一关
							</button>
							<button class="modal-button replay-btn" @click="replayLevel">
								再玩一次
							</button>
							<button v-if="!hasNextLevel" class="modal-button restart-btn" @click="restartGame">
								返回第一关
							</button>
						</div>
					</div>
				</div>
			</div>
		</transition>

		<div class="button">
			<div class="button_middle">
				<button @click="move('left')">←</button>
				<div class="middle_two">
					<button @click="move('up')">↑</button>
					<button @click="move('down')">↓</button>
				</div>
				<button @click="move('right')">→</button>
			</div>

			<div class=button_right>
				<button @click="reset">重置游戏</button>
				<button class="startgame" @click="startgame">开始游戏</button>
				<button class="back" @click="back">返回首页</button>
			</div>
		</div>

		<!-- 规则 -->
		<div class="rule-model" v-if="Gameplay">
			<div class="rule">
				<div class="rule_title">
					<h2>游戏玩法</h2>
					<button @click="tiggleset">关闭</button>
				</div>
				<div class="rule-last">
					<h3>
						<span>1、基本规则</span><br>
						<span style="text-indent: 1vh;padding-bottom: 1vh">
							在一个小空间内，要求在规定时间内把箱子推到指定位置，稍有不注意便会无法移动或导致通道堵住的情况，所以请巧妙利用有限空间和通道合理安排移动次序及位置，祝你游戏成功
						</span>
					</h3>
					<h3>
						<span style="line-height:0.1;">2、操作方法</span>
						<span style="text-indent: 1vh;"><br>
							手机端：点击屏幕上下左右键，控制游戏角色，点击方向按键即主角移动方向，每点击一次，主角就移动一次。
						</span><br>
						<span style="text-indent: 1vh;padding-bottom: 1vh">
							电脑端：点击屏幕上下左右键，或者键盘上下左右键，都可控制游戏角色，点击方向按键即主角移动方向，每点击一次，主角就移动一次。
						</span>
					</h3>
					<h3>
						<span>3、注意事项</span><br>
						<span>
							箱子只能以被推的方式移动，不能以被拉的方式移动;不可以同时推动两个及其以上的箱子。当推到墙壁的位置则无法继续推行，只能换方向移动，所以一定要注意!
						</span>
					</h3>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
	import {
		useRouter
	} from "vue-router";
	import {
		ref,
		computed,
		onMounted,
		onBeforeUnmount,
		watch
	} from "vue";
  import Gamemap from './Gamemap.vue';
	import {
		SokobanGame
	} from '@/js/game.js';
	import {
		LEVELS
	} from '@/js/levels.js';
	import backgroundMusic from '@/assets/audio/background.mp3'; // 引入背景音乐
	import levelCompleteSound from '@/assets/audio/win.mp3'; // 引入关卡通过音效

	const router = useRouter();
	const showsettings = ref(false);
	const Gameplay = ref(false);

	// 游戏状态
	const game = ref(null);
	const moves = ref(0);
	const gamemap = ref([]);
	const showCompletion = ref(false);
	const isCompleted = ref(false);
	const progress = ref(0);
	const currentLevelName = computed(() => LEVELS[currentLevel.value]?.name || ` ${currentLevel.value} `);
	const hasNextLevel = computed(() => currentLevel.value < LEVELS.length - 1);
	let progressInterval;

	const currentLevel = ref(1);
	const currentSteps = ref(0)
	const showRankingList = ref(false)

	// 音乐和音效控制
	const isMusicOn = ref(true);
	const isSoundEffectOn = ref(true);
	const bgMusic = ref(null);
	const levelCompleteAudio = ref(null);
	const audioInitialized = ref(false); // 音频是否已初始化
	// 初始化音频
	const initializeAudio = () => {
		if (audioInitialized.value) return;

		bgMusic.value = new Audio(backgroundMusic);
		levelCompleteAudio.value = new Audio(levelCompleteSound);

		bgMusic.value.loop = true;
		bgMusic.value.volume = 0.5;

		audioInitialized.value = true;

		// 尝试播放背景音乐
		if (isMusicOn.value) {
			playBackgroundMusic();
		}

		// 移除事件监听器，避免重复初始化
		window.removeEventListener('click', initializeAudio);
	};
	const playBackgroundMusic = () => {
		if (!audioInitialized.value || !isMusicOn.value) return;

		bgMusic.value.play().catch(e => {
			console.error('Failed to play background music:', e);
			isMusicOn.value = false;
		});
	};
	const playLevelCompleteSound = () => {
		if (!audioInitialized.value || !isSoundEffectOn.value) return;

		levelCompleteAudio.value.currentTime = 0;
		levelCompleteAudio.value.play().catch(e => {
			console.error('Failed to play level complete sound:', e);
			isSoundEffectOn.value = false;
		});
	};
	// 监听音乐和音效开关变化
	watch(isMusicOn, (newValue) => {
		if (newValue) {
			playBackgroundMusic();
		} else {
			bgMusic.value?.pause();
		}
	});

	// 玩家数据
	const currentPlayer = ref({
		id: 'user_' + Date.now(),
		username: '玩家' + Math.floor(Math.random() * 1000),
		maxLevel: 1,
		totalSteps: 0,
		levelSteps: [],
		rank: null,
		registerTime: Date.now() // 新增注册时间
	});

	// 排行榜数据
	const players = ref([]);
	// 排序选项
	const sortBy = ref('maxLevelDesc');
	// 排序后的玩家列表
	const sortedPlayers = computed(() => {
		let sorted = [...players.value];
		if (sortBy.value === 'maxLevelDesc') {
			sorted.sort((a, b) => {
				if (b.maxLevel !== a.maxLevel) return b.maxLevel - a.maxLevel;
				if (a.totalSteps !== b.totalSteps) return a.totalSteps - b.totalSteps;
			});
		} else if (sortBy.value === 'totalStepsAsc') {
			sorted.sort((a, b) => a.totalSteps - b.totalSteps);
		}
		return sorted;
	});

	// 加载游戏数据
	const loadGameData = () => {
		// 加载游戏进度
		const savedProgress = localStorage.getItem('gameProgress');
		if (savedProgress) {
			const {
				level,
				steps,
				totalSteps,
				levelSteps // 加载每关步数
			} = JSON.parse(savedProgress);
			currentLevel.value = level || 1;
			currentSteps.value = steps || 0;
			currentPlayer.value.totalSteps = totalSteps || [];
			currentPlayer.value.levelSteps = levelSteps || []; // 初始化每关步数数组
		}

		// 加载排行榜数据
		const savedRanking = localStorage.getItem('gameRanking');
		if (savedRanking) {
			players.value = JSON.parse(savedRanking);
		}

		// 确保当前玩家在排行榜中
		if (!players.value.some(p => p.id === currentPlayer.value.id)) {
			players.value.push({
				...currentPlayer.value
			});
		}
		updateRanking();
	};

	// 更新排行榜
	const updateRanking = () => {
		// 更新当前玩家数据
		const index = players.value.findIndex(p => p.id === currentPlayer.value.id);
		if (index === -1) {
			players.value.push({
				...currentPlayer.value
			});
		} else {
			players.value[index] = {
				...currentPlayer.value
			};
		}

		// 保存数据
		saveRankingData();
		updatePlayerRank();
	};

	//保存排行榜数据
	const saveRankingData = () => {
		localStorage.setItem('gameRanking', JSON.stringify(players.value));
		localStorage.setItem('currentPlayer', JSON.stringify(currentPlayer.value));
	};

	// 保存游戏进度
	const saveGameProgress = () => {
		localStorage.setItem('gameProgress', JSON.stringify({
			level: currentLevel.value,
			steps: currentSteps.value,
			totalSteps: currentPlayer.value.totalSteps,
			levelSteps: currentPlayer.value.levelSteps // 保存每关步数
		}));
	};

	// 更新玩家排名
	const updatePlayerRank = () => {
		const sorted = [...players.value].sort((a, b) => {
			if (b.maxLevel !== a.maxLevel) return b.maxLevel - a.maxLevel;
			if (a.totalSteps !== b.totalSteps) return a.totalSteps - b.totalSteps;
		});

		currentPlayer.value.rank = sorted.findIndex(p => p.id === currentPlayer.value.id) + 1 || null;
	};

	// 开始新关卡
	const startNewLevel = (level) => {
		currentLevel.value = level;
		currentSteps.value = 0;
		saveGameData();
	};

	// 记录玩家移动
	const recordPlayerMove = () => {
		currentSteps.value++;

		// 确保音频已初始化
		if (!audioInitialized.value) {
			initializeAudio();
		}

		// 播放移动音效
		if (isSoundEffectOn.value) {
			// 确保音效可以重新播放
			if (levelCompleteAudio.value && !levelCompleteAudio.value.paused) {
				levelCompleteAudio.value.pause();
				levelCompleteAudio.value.currentTime = 0;
			}
		}

		saveGameData();
	};

	// 完成关卡处理
	const completeLevel = () => {
		// 记录当前关卡的步数
		currentPlayer.value.levelSteps[currentLevel.value - 1] = currentSteps.value;
		// 正确累计步数
		currentPlayer.value.totalSteps += currentSteps.value;

		// 更新玩家进度
		currentPlayer.value.maxLevel = Math.max(currentPlayer.value.maxLevel, currentLevel.value);

		// 更新排行榜数据
		saveRankingData();
		updatePlayerRank();

		// 保存游戏进度
		saveGameProgress();

		// 确保音频已初始化
		if (!audioInitialized.value) {
			initializeAudio();
		}

		// 通关检查
		if (currentLevel.value === 10) {
			alert(`恭喜通关！总步数: ${currentPlayer.value.totalSteps}`);
		} else {
			// 进入下一关
			currentLevel.value += 1;
			currentSteps.value = 0;
			saveGameProgress();
		}

		// 播放完成音效
		playLevelCompleteSound();

		// 显示完成提示
		showLevelComplete();
	};

	// 排行榜控制
	const toggleRankingList = () => {
		showRankingList.value = !showRankingList.value;
		if (showRankingList.value) {
			updatePlayerRank();
			updateRanking();
		}
	}

	const closeRankingList = () => {
		showRankingList.value = false
	}

	const initGame = () => {
		// 确保当前关卡存在
		if (!LEVELS[currentLevel.value - 1]) {
			console.error('关卡不存在:', currentLevel.value);
			// 可以选择回退到第一个关卡
			currentLevel.value = 1;
		}

		game.value = new SokobanGame(LEVELS[currentLevel.value]);
		updateGameState();
	};

	const updateGameState = () => {
		gamemap.value = game.value.map;
		moves.value = game.value.moves;
		isCompleted.value = game.value.isCompleted;

		// 每次移动都更新步数
		currentSteps.value = moves.value;
	};

	const move = (direction) => {
		const result = game.value.move(direction);
		updateGameState();

		if (result?.levelCompleted) {
			showLevelComplete();
		}
	};

	const reset = () => {
		game.value.reset();
		updateGameState();
		showCompletion.value = false;
	};

	const showLevelComplete = () => {
		showCompletion.value = true;
		progress.value = 0;

		if (!hasNextLevel.value) return;

		playLevelCompleteSound();

		// 进度条动画
		progressInterval = setInterval(() => {
			progress.value += 2;
			if (progress.value >= 100) {
				clearInterval(progressInterval);
				if (hasNextLevel.value) {
					currentLevel.value++;
					initGame();
				}
				showCompletion.value = false;
			}
		}, 30); // 总共3秒自动进入
	};

	const goNextLevelNow = () => {
		clearInterval(progressInterval);
		if (hasNextLevel.value) {
			currentLevel.value += 1;
			initGame();
		}
		showCompletion.value = false;
	};

	const replayLevel = () => {
		clearInterval(progressInterval);
		reset();
		showCompletion.value = false;
	};

	const restartGame = () => {
		clearInterval(progressInterval);
		currentLevel.value = 0;
		initGame();
		showCompletion.value = false;
	};

	const handleKeyDown = (e) => {
		const keyMap = {
			'ArrowUp': 'up',
			'ArrowDown': 'down',
			'ArrowLeft': 'left',
			'ArrowRight': 'right',
			'w': 'up',
			's': 'down',
			'a': 'left',
			'd': 'right'
		};

		if (keyMap[e.key]) {
			e.preventDefault();
			move(keyMap[e.key]);
		}
	};

	function back() {
		uni.navigateTo({
			url: '/pages/start/start'
		});
	}

	function settinter() {
		showsettings.value = true;
	}

	function tiggleset() {
		showsettings.value = false;
		Gameplay.value = false;
	}

	function startgame() {
		showsettings.value = true;
	}

	function introduction() {
		Gameplay.value = true;
	}

	onMounted(() => {
		initGame();
		window.addEventListener('keydown', handleKeyDown);

		loadGameData();
		// 监听用户点击事件，用于初始化音频
		window.addEventListener('click', initializeAudio);
	});

	onBeforeUnmount(() => {
		window.removeEventListener('keydown', handleKeyDown);
		window.removeEventListener('click', initializeAudio);
		bgMusic.value?.pause();
	});
</script>

<style scoped>
	.Game_container {
		padding: 10px;
		width: 100%;
		height: 100%;
	}

	.title {
		display: flex;
		justify-content: space-between;
    align-items: center;

		.set {
			padding: 3px;
			display: flex;
			font-size: 0.5em;
		}

		button:hover {
			transition: all 0.1s ease 0s;
			transform: scale(1.3);
			background-color: #b2dea1;
		}

		.steps {
			display: flex;
		}
	}

	.settings {
		z-index: 9999;
		position: fixed;
		flex-direction: column;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: rgba(0, 0, 0, 0.8);
		display: flex;
    align-items: center;
		justify-content: center;

		h3 {
			font-size: 1em;
			margin: 0;
		}

		ul {
			font-size: 1em;
			margin: 0.3em;
		}

		button {
			font-size: 0.5em;
			margin: 0.3em;
		}

		button:hover {
			transition: all 0.1s ease 0s;
			transform: scale(1.1);
			background-color: #ffa800;
		}
	}

	.game-container {
		display: flex;
		top: 10px;
		width: 100%;

		.button_left {
			display: inline-flex;
			flex-direction: column;
			margin-right: auto;

			button {
				width: 40%;
				font-size: 2vh;
				font-weight: bold;
				display: flex;
				justify-content: center;
			}

			button:hover {
				transition: all 0.1s ease 0s;
				transform: scale(1);
				background-color: #b2dea1;
			}
		}

		.map {
			display: flex;
			position: absolute;
      width: 80%;
			left: 50%;
			transform: translate(-50%, 30%);
		}
	}

	.modal-mask {
		position: fixed;
		z-index: 9998;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
    align-items: center;
		transition: opacity 0.3s ease;

		.modal-wrapper {
			width: 70%;
			max-width: 20vh;
			margin: 0 auto;

			.modal-container {
				width: 100%;
				margin: 0 auto;
				padding: 20px 30px;
				background-color: indianred;
				border-radius: 12px;
				box-shadow: 0 2px 20px rgba(0, 0, 0, 0.33);
				transition: all 0.3s ease;

				.modal-header h2 {
					color: #42b983;
					text-align: center;
					font-size: 0.6vh;
				}

				.modal-body {
					margin: 20px 0;
					text-align: center;
					font-size: 0.5vh;

					.congrats-message {
						font-size: 1vh;
						color: #ff9100;
						margin-top: 15px;
						font-weight: bold;
						animation: pulse 1.5s infinite;
					}

					.progress-container {
						margin: 20px 0;

						.progress-bar {
							height: 10px;
							background: #e0e0e0;
							border-radius: 5px;
							overflow: hidden;
							margin-bottom: 8px;

							.progress-fill {
								height: 100%;
								background: linear-gradient(90deg, #42b983, #66cdaa);
								transition: width 0.1s linear;
							}
						}
					}
				}

				.modal-footer {
					display: flex;
					justify-content: center;
					flex-wrap: wrap;
					gap: 10px;
					margin-top: 20px;
					margin-bottom: 20px;

					.modal-button {
						padding: 10px 20px;
						border: none;
						border-radius: 6px;
						font-size: 0.5vh;
						cursor: pointer;
						transition: all 0.2s;
					}

					.next-btn {
						background-color: #42b983;
						color: white;
					}

					.replay-btn {
						background-color: #4169E1;
						color: #333;
					}

					.restart-btn {
						background-color: #4169E1;
						color: white;
					}
				}

			}
		}
	}

	@keyframes pulse {
		0% {
			transform: scale(1);
		}

		50% {
			transform: scale(1.05);
		}

		100% {
			transform: scale(1);
		}
	}

	.modal-button:hover {
		transform: translateY(-2px);
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
	}

	.modal-enter-from .modal-container,
	.modal-leave-to .modal-container {
		transform: scale(0.9);
	}

	.rule-model {
		z-index: 9999;
		position: fixed;
		flex-direction: column;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: rgba(0, 0, 0, 0.8);
		display: flex;
    align-items: center;
		justify-content: center;

		.rule {
			justify-content: space-between;
			width: 60%;
			font-size: 1vh;
			overflow-y: auto;
			color: black;
			background: rgb(253, 253, 253);
			padding: 1vh;
			border-radius: 8px;
			line-height: 1.3vh;

			.rule_title {
				display: flex;
				justify-content: space-between;

				button {
					display: flex;
          align-items: center;
					font-size: 1vh;
					transition: background-color 1s linear, color 1s linear;
				}

				button:hover {
					transition: all 0.1s ease 0s;
					transform: scale(1.1);
					background-color: #ffa800;
				}
			}

			.rule-last {
				h3 {
					top: 0;
				}
			}
		}
	}

	.button {
		display: flex;
		position: absolute;
		bottom: 1vh;
		right: 10px;
		width: 100%;

		.button_middle {
			width: 10vh;
			display: flex;
			position: absolute;
			left: 50%;
			transform: translate(-50%, 30%);

			.middle_two {
				display: inline-flex;
				flex-direction: column;
				width: 100%;
			}

			button {
				font-size: 0.8vh;
				display: flex;
        align-items: center;
				justify-content: center;
			}
		}

		.button_right {
			display: inline-flex;
			margin-left: auto;
			flex-direction: column;

			button {
				font-size: 0.5vh;
				display: flex;
        align-items: center;
				justify-content: center;
			}
		}
	}

	/* 排行榜弹窗样式 */
	.ranking-popup {
		top: 70px;
		left: 200px;
		width: 100%;
		background-color: rgba(143, 140, 140, 0.5);
		border-radius: 10px;
		z-index: 100;
		overflow: hidden;
		animation: fadeIn 0.3s ease;
	}

	.ranking-header {
		display: flex;
		justify-content: space-between;
    align-items: center;
		padding: 15px 20px;
		background-color: #4a6baf;
		color: white;

		h3 {
			margin: 0;
			font-size: 0.5vh;
			font-weight: 500;
		}
	}

	.close-btn {
		font-size: 0.5vh;
		cursor: pointer;
		transition: transform 0.2s;
	}

	.ranking-content {
		padding: 0;
		max-height: 10vh;
		overflow-y: auto;

		table {
			width: 100%;
			border-collapse: collapse;
		}

		th,
		td {
			padding: 12px 16px;
			text-align: left;
			border-bottom: 1px solid #eaeaea;
		}

		th {
			background-color: #f8f9fa;
			font-size: 0.6vh;
			font-weight: 500;
			color: #4a6baf;
			position: sticky;
			top: 0;
		}

		tr:nth-child(even) {
			background-color: #4a6baf;
		}

		tr:hover {
			background-color: #646667;
		}
	}
</style>
